package sdk.webview.fmc.com.fmcsdk.util;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Application;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.preference.PreferenceManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DecimalFormat;

import sdk.webview.fmc.com.fmcsdk.R;
import sdk.webview.fmc.com.fmcsdk.app.FMCApplication;

/**
 * Created by ydm on 2018/1/11.
 * 下载文件
 */

public class DownloadFileManager {
    /**
     * 进度条
     */
    private ProgressBar mProgress;
    // 下载数值
    private TextView mProgressText;
    /**
     * 下载的提示框
     */
    private Dialog downloadDialog;
    // 终止标记
    private boolean interceptFlag;
    /**
     * 上下文
     */
    private Context mContext;
    /**
     * 下载的文件名称
     */
    private String downloadeName;
    /**
     * 下载的url
     */
    private String downloadUrl;
    /**
     * 下载的字节大小
     */
    private String downloadByte;
    // 下载线程
    private Thread downLoadThread;
    // 下载文件保存路径
    private String savePath = "";
    // 文件保存完整路径
    private String mFilePath = "";
    // 临时下载文件路径
    private String tmpFilePath = "";
    // 下载文件大小
    private String mFileSize;
    // 已下载文件大小
    private String tmpFileSize;
    // 进度值
    private int progress;
    private final int DOWN_NOSDCARD = 0;
    private final int DOWN_UPDATE = 1;
    private final int DOWN_OVER = 2;
    private final int DOWN_ERROR = 3;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWN_UPDATE://更新下载进度
                    mProgress.setProgress(progress);
                    mProgressText.setText(tmpFileSize + "/" + mFileSize);
                    break;
                case DOWN_OVER://下载完成
                    downloadDialog.dismiss();
                    //打开文件
                    openFile();
                    break;
                case DOWN_NOSDCARD://没有挂载SD卡
                    downloadDialog.dismiss();
                    ToastUtils.showShort(mContext, mContext.getResources().getString(R.string.msg_not_download_file));
                    break;
                case DOWN_ERROR://下载失败
                    downloadDialog.dismiss();
                    String message = (String) msg.obj;
                    //弹出下载失败的提示框
                    showErrorDialog(message);
                    break;

            }
        }

        ;
    };

    //下载失败提示框
    private void showErrorDialog(String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle(R.string.dialog_prompt);
        builder.setMessage(message);
        builder.setNegativeButton(mContext.getString(R.string.ok), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.show();
    }

    /**
     * 显示下载文件的进度条
     */
    public void showDownloadDialog(Context mContext, String downloadeName, String downloadUrl, String downloadByte) {
        this.mContext = mContext;
        this.downloadeName = downloadeName;
        this.downloadUrl = downloadUrl;
        this.downloadByte = downloadByte;
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle(mContext.getString(R.string.downing_file));
//        builder.setCancelable(false);
        final LayoutInflater inflater = LayoutInflater.from(mContext);

        View v = inflater.inflate(R.layout.update_progress, null);
        mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
        mProgressText = (TextView) v.findViewById(R.id.update_progress_text);
        builder.setView(v);
        builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                dialog.dismiss();
                interceptFlag = true;
            }
        });
        downloadDialog = builder.create();
        downloadDialog.setCanceledOnTouchOutside(false);
        downloadDialog.show();
        //开始下载
        downloadFile();
    }

    /**
     * 开始下载文件
     */
    private void downloadFile() {
        if (!NetworkUtils.isAvailable(mContext)) {
            Message msg = mHandler.obtainMessage(DOWN_ERROR);
            msg.obj = mContext.getString(R.string.msg_download_file_error);
            msg.sendToTarget();
            return;
        }
        downLoadThread = new Thread(mdownFileRunnable);
        downLoadThread.start();
    }

    private Runnable mdownFileRunnable = new Runnable() {
        @Override
        public void run() {
            try {
                String[] name = downloadeName.split("\\.");
                String tmpFileName = name[0] + ".tmp";
                // 判断是否挂载了SD卡
                String storageState = Environment.getExternalStorageState();
                if (storageState.equals(Environment.MEDIA_MOUNTED)) {
                    // Environment.getExternalStorageDirectory().getAbsolutePath()
                    String storePath = mContext.getApplicationContext().getExternalCacheDir().getAbsolutePath() + "/fmc/" + PreferenceManager.getDefaultSharedPreferences(mContext).getString(Constant.APP_NAME, "fmsdk");
                    savePath = storePath + Constant.H5FILEPATH;
                    File file = new File(savePath);
                    if (!file.exists()) {
                        file.mkdirs();
                    }

                    mFilePath = savePath + "/" + downloadeName;
                    tmpFilePath = savePath + "/" + tmpFileName;
                }
                // 没有挂载SD卡，无法下载文件
                if (mFilePath == null || mFilePath == "") {
                    mHandler.sendEmptyMessage(DOWN_NOSDCARD);
                    return;
                }
                File mFile = new File(mFilePath);
                // 是否已下载更新文件
                if (mFile.exists()) {
                    downloadDialog.dismiss();
                    openFile();
                    return;
                }

                File tmpFile = new File(tmpFilePath);
//                if (!tmpFile.exists()) {
//                    tmpFile.createNewFile();
//                }
                FileOutputStream fos = new FileOutputStream(tmpFile);

                URL url = new URL(downloadUrl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                //宝安区https访问需要加载证书
                if (downloadUrl.startsWith("https")) {
                    boolean isSdk = PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean(Constant.IS_SDK, false);
                    if (!isSdk) {
                        String appName = (String) Utility.getMetaData(mContext, Constant.APP_NAME);
                        String isHttps = (String) Utility.getMetaData(mContext, Constant.IS_HTTPS_TEST);
//                        if (Constant.APP_NAME_BAQ.equals(appName)||isHttps.equals("fmc_true")) {
//                            HttpsManager.setHttpsConnection(conn, mContext);
//                        }
                    }

                }
                conn.setRequestProperty("Accept-Encoding", "identity");
                conn.connect();
                int length = Integer.parseInt(downloadByte);
                InputStream is = conn.getInputStream();
                // 显示文件大小格式：2个小数点显示
                DecimalFormat df = new DecimalFormat("0.00");
                // 进度条下面显示的总文件大小
                mFileSize = df.format((float) length / 1024 / 1024) + "MB";

                int count = 0;
                byte buf[] = new byte[1024];

                do {
                    int numread = is.read(buf);
                    count += numread;
                    // 进度条下面显示的当前下载文件大小
                    tmpFileSize = df.format((float) count / 1024 / 1024) + "MB";
                    // 当前进度值
                    progress = (int) (((float) count / length) * 100);
                    // 更新进度
                    mHandler.sendEmptyMessage(DOWN_UPDATE);
                    if (numread <= 0) {
                        if (tmpFile.renameTo(mFile)) {
                            // 通知安装
                            mHandler.sendEmptyMessage(DOWN_OVER);
                        }
                        break;
                    }
                    fos.write(buf, 0, numread);
                } while (!interceptFlag);// 点击取消就停止下载
                if (tmpFile.exists()) {
                    tmpFile.delete();
//                    ToastUtils.showShort(mContext, mContext.getResources().getString(R.string.canecl_download_success));
                }

                fos.close();
                is.close();
            } catch (MalformedURLException e) {
                Message msg = mHandler.obtainMessage(DOWN_ERROR);
                msg.obj = mContext.getString(R.string.not_download_path);
                msg.sendToTarget();
            } catch (IOException e) {
                if (e instanceof FileNotFoundException) {
                    Message msg = mHandler.obtainMessage(DOWN_ERROR);
                    msg.obj = mContext.getString(R.string.file_does_not);
                    msg.sendToTarget();
//                    //下载失败
//                    mHandler.sendEmptyMessage();
                }

            }

        }
    };

    /**
     * 打开文件
     */
    private void openFile() {
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());

        File file = new File(mFilePath);
        if (!file.exists()) {
            return;
        }
        try {
//            Uri contentUri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".fileprovider", file);
//            Intent intent = new Intent();
//            intent.setAction(android.content.Intent.ACTION_VIEW);
//            intent.setDataAndType(contentUri, getMIMEType(file)); //Uri.fromFile(file)
//            mContext.startActivity(intent);
            openFile(mContext, mFilePath);
        } catch (Exception e) {
            if (e instanceof FileNotFoundException) {
                Message msg = mHandler.obtainMessage(DOWN_ERROR);
                msg.obj = mContext.getString(R.string.install_open);
                ;
                msg.sendToTarget();
//                    //下载失败了
//                    mHandler.sendEmptyMessage();
            }
//            Toast.makeText(mContext,R.string.install_open,Toast.LENGTH_SHORT).show();
        }

    }

    public void openFile(Context context, String fileFullName) {
        File apkFile = new File(fileFullName);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        int bt = Build.VERSION.SDK_INT;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", apkFile);
            intent.setDataAndType(contentUri, getMIMEType(apkFile));
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile), getMIMEType(apkFile));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        if (context.getPackageManager().queryIntentActivities(intent, 0).size() > 0) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }
    }

    private static String getMIMEType(File f) {
        String type = "";
        String fName = f.getName();
        String end = fName.substring(fName.lastIndexOf(".") + 1, fName.length()).toLowerCase();
        if (end.equals("m4a") || end.equals("mp3") || end.equals("mid") || end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
            type = "audio";
        } else if (end.equals("3gp") || end.equals("mp4")) {
            type = "video";
        } else if (end.equals("jpg") || end.equals("gif") || end.equals("png") || end.equals("jpeg") || end.equals("bmp")) {
            type = "image/*";
        } else if (end.equals("doc") || end.equals("docx")) {
            type = "application/msword";
        } else if (end.equals("ppt") || end.equals("pot") || end.equals("pps")) {
            type = "application/vnd.ms-powerpoint";
        } else if (end.equals("xla") || end.equals("xlc") || end.equals("xlm") || end.equals("xls") || end.equals("xlt") || end.equals("xlw") || end.equalsIgnoreCase("xlsx")) {
            type = "application/vnd.ms-excel";
        } else if (end.equals("xll")) {
            type = "application/x-excel";
        } else if (end.equals("pdf")) {
            type = "application/pdf";
        } else if (end.equals("zip")) {
            type = "application/zip";
        } else if (end.equals("rar")) {
            type = "application/x-rar-compressed";
        } else if (end.equals("apk")) {
            type = "application/vnd.android.package-archive";
        } else if (end.equals("txt")) {
            type = "text/plain";
        } else {
            type = "/*";
        }
        return type;
    }


    private boolean checkWritePermission() {
        int permission = ActivityCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        return permission == PackageManager.PERMISSION_GRANTED;
    }
}

